package com.zywl.api;

import com.github.pagehelper.util.StringUtil;
import com.zywl.core.beans.*;
import com.zywl.core.beans.Dictionary;
import com.zywl.service.*;
import com.zywl.utils.models.JsonResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.MapUtil;
import com.zywl.utils.utils.MsgUtils;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.DemandForm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/api/demand/")
public class DemandApi extends BaseController {
    @Autowired
    private DemandService demandService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private AssociationService associationService;


    @ResponseBody
    @RequestMapping("list")
    public PageResult list(Demand from, PageData pageData){
        PageResult pageResult = null;
        try {
            if(from.getDedAssociationid() == null){
                return pageResult.error("请输入协会id");
            }
            if(from.getDedCompanyId() == null){
                return pageResult.error("请输入公司id");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("dedAssociationid",from.getDedAssociationid());
            if(from.getDedMemberId() != null){
                map.put("dedCompanyId",from.getDedCompanyId());
            }else{
                map.put("dedCompanyIdNot",from.getDedCompanyId());
            }
            if(from.getDedName() != null){
                map.put("dedName",from.getDedName());
            }
            if(from.getDedIndustrys() != null){
                map.put("dedIndustrys",from.getDedIndustrys());
            }
            if(from.getDedTags() != null){
                map.put("dedTags",from.getDedTags());
            }
            map.put("dedStt","0");
            pageResult = putToResult(demandService.getPageInfo(map, pageData));
        }catch (Exception e){
            logger.error("添加失败",e);
            pageResult.error("查询失败");
        }
        return pageResult;
    }

    @ResponseBody
    @RequestMapping("create")
    public JsonResult create(Demand from){
        JsonResult jr = new JsonResult();
        Date date = new Date();
        try {
            if(from.getDedAssociationid() == null){
                return jr.error("请输入协会id");
            }
            if(from.getDedMemberId() == null){
                return jr.error("请输入会员id");
            }
            if(from.getDedCompanyId() == null){
                Member member = memberService.getById(from.getDedMemberId());
                if(member.getMebCompanyId() == null){
                    return jr.error("请先添加公司信息！");
                }
            }

            from.setDedStt("0");
            from.setDedCreateTime(date);
            from.setDedModifyTime(date);
            demandService.save(from);

            //匹配公司
            List<String> industrysList = new ArrayList<>();
            List<String> tagList = new ArrayList<>();
            if(StringUtils.isNotEmpty(from.getDedIndustrys())){
                String[] industrys = from.getDedIndustrys().split(",");
                for (String s : industrys){
                    industrysList.add(","+s+",");
                }
            }
            if(StringUtils.isNotEmpty(from.getDedTags())){
                String[] tags = from.getDedTags().split(",");
                for (String s : tags){
                    tagList.add(","+s+",");
                }
            }
            List<Company> companyList = companyService.getByMatch(from.getDedCompanyId(),industrysList,tagList);
            //第一次匹配会向匹配到的公司负责人发送短信
            Association association = associationService.getById(from.getDedAssociationid());
            for (Company company : companyList){
                MsgUtils.send(company.getComMobile(),association.getAssWxAppName());
            }
            jr.success("添加成功",from.getDedId());
        }catch (Exception e){
            logger.error("添加失败",e);
            jr.error("添加失败");
        }
        return jr;
    }

    @ResponseBody
    @RequestMapping("detail")
    public JsonResult detail(String id){
        JsonResult jr = new JsonResult();
        try {
            if(StringUtils.isEmpty(id)){
                return jr.error("请输入id");
            }
            Demand demand = demandService.getById(Long.valueOf(id));
            DemandForm demandForm = new DemandForm();
            BeanUtils.copyProperties(demand, demandForm);
            List<Dictionary> dictionaryList = dictionaryService.getDictionaryByType("indu");
            List<Dictionary> tagsList = dictionaryService.getDictionaryByType("tags");
            Map<String,String> map = new HashMap<>();
            for (Dictionary dictionary : dictionaryList){
                map.put(dictionary.getDisCode(),dictionary.getDisCodeName());
            }
            Map<String,String> tagmap = new HashMap<>();
            for (Dictionary dictionary : tagsList){
                tagmap.put(dictionary.getDisCode(),dictionary.getDisCodeName());
            }
            String[] indus = demand.getDedIndustrys().split(",");
            String induName = "";
            for (String str : indus){
                if(StringUtil.isNotEmpty(str)){
                    induName += map.get(str) + ",";
                }
            }
//            demandForm.setDedIndustrys(demand.getDedIndustrys().substring(1,demand.getDedIndustrys().length()-1));
            demandForm.setDedIndustrysName(induName.substring(0,induName.length()-1));

            String[] tags = demand.getDedTags().split(",");
            String tagsName = "";
            for (String str : tags){
                if(StringUtil.isNotEmpty(str)){
                    tagsName += tagmap.get(str) + ",";
                }
            }
//            demandForm.setDedTags(demand.getDedTags().substring(1,demand.getDedTags().length()-1));
            demandForm.setDedTagsName(tagsName.substring(0,tagsName.length()-1));
            jr.success("操作成功",demandForm);
        }catch (Exception e){
            logger.error("操作失败",e);
            jr.error("操作失败");
        }
        return jr;
    }

    @ResponseBody
    @RequestMapping("match")
    public JsonResult match(String id){
        JsonResult jr = new JsonResult();
        try {
            if(StringUtils.isEmpty(id)){
                return jr.error("请输入id");
            }
            Demand demand = demandService.getById(Long.valueOf(id));
            if(demand == null){
                return jr.error("该数据不存在，请查证！");
            }
            //匹配公司
            List<String> industrysList = new ArrayList<>();
            List<String> tagList = new ArrayList<>();
            if(StringUtils.isNotEmpty(demand.getDedIndustrys())){
                String[] industrys = demand.getDedIndustrys().split(",");
                for (String s : industrys){
                    industrysList.add(","+s+",");
                }
            }
            if(StringUtils.isNotEmpty(demand.getDedTags())){
                String[] tags = demand.getDedTags().split(",");
                for (String s : tags){
                    tagList.add(","+s+",");
                }
            }
            List<Company> companyList = companyService.getByMatch(demand.getDedCompanyId(),industrysList,tagList);
            if(companyList.size() > 0){
                List<Dictionary> dictionaryList = dictionaryService.getDictionaryByType("indu");
                List<Dictionary> tagsList = dictionaryService.getDictionaryByType("tags");
                Map<String,String> map = new HashMap<>();
                for (Dictionary dictionary : dictionaryList){
                    map.put(dictionary.getDisCode(),dictionary.getDisCodeName());
                }
                Map<String,String> tagmap = new HashMap<>();
                for (Dictionary dictionary : tagsList){
                    tagmap.put(dictionary.getDisCode(),dictionary.getDisCodeName());
                }
                for (Company company : companyList){
                    if(StringUtils.isNotEmpty(company.getComIndustry())){
                        String[] indus = company.getComIndustry().split(",");
                        String induName = "";
                        for (String str : indus){
                            if(StringUtil.isNotEmpty(str)){
                                induName += map.get(str) + ",";
                            }
                        }
                        company.setComIndustry(induName.substring(0,induName.length()-1));
                    }
                    if(StringUtils.isNotEmpty(company.getComTag())){
                        String[] tags = company.getComTag().split(",");
                        String tagsName = "";
                        for (String str : tags){
                            if(StringUtil.isNotEmpty(str)){
                                tagsName += tagmap.get(str) + ",";
                            }
                        }
//                        company.setComTag(company.getComTag().substring(1,company.getComTag().length()-1));
                        company.setComTag(tagsName.substring(0,tagsName.length()-1));
                    }
                }
            }
            jr.success("操作成功",companyList);
        }catch (Exception e){
            logger.error("操作失败",e);
            jr.error("操作失败");
        }
        return jr;
    }

    @ResponseBody
    @RequestMapping("modify")
    public JsonResult modify(Demand from){
        JsonResult jr = new JsonResult();
        Date date = new Date();
        try {
            if(from.getDedId() == null){
                return jr.error("请输入id");
            }
            Demand demand = demandService.getById(Long.valueOf(from.getDedId()));
            if(StringUtils.isNotEmpty(from.getDedName())){
                demand.setDedName(from.getDedName());
            }
            if(StringUtils.isNotEmpty(from.getDedIndustrys())){
                demand.setDedIndustrys(from.getDedIndustrys());
            }
            if(StringUtils.isNotEmpty(from.getDedTags())){
                demand.setDedTags(from.getDedTags());
            }
            if(StringUtils.isNotEmpty(from.getDedContent())){
                demand.setDedContent(from.getDedContent());
            }
            if(StringUtils.isNotEmpty(from.getDedRemark())){
                demand.setDedRemark(from.getDedRemark());
            }
            demand.setDedModifyTime(date);
            demandService.update(demand);
            jr.success("修改成功");
        }catch (Exception e){
            logger.error("修改失败",e);
            jr.error("修改失败");
        }
        return jr;
    }

    @ResponseBody
    @RequestMapping("remove")
    public JsonResult remove(String id){
        JsonResult jr = new JsonResult();
        Date date = new Date();
        try {
            if(StringUtils.isEmpty(id)){
                return jr.error("请输入id");
            }
            Demand demand = demandService.getById(Long.valueOf(id));
            demand.setDedStt("1");
            demand.setDedModifyTime(date);
            demandService.update(demand);
            jr.success("删除成功");
        }catch (Exception e){
            logger.error("删除失败",e);
            jr.error("删除失败");
        }
        return jr;
    }

}
